#import "TxPlugin.h"
#import "WXApi.h"
#import "Constant/Const.h"
#import "FlutterWxApiHandler.h"
#import "FlutterQQApiHandler.h"
#import "FlutterWxResponseHandler.h"
#import "FlutterQQResponseHandler.h"
#import "QQSdkCallManager.h"

@interface TxPlugin ()
{
    FlutterWxApiHandler *wxApiHandler; // 微信api操作
    FlutterQQApiHandler *qqApiHandler; // QQapi操作
    FlutterMethodChannel *shareChannel;
}

@end

@implementation TxPlugin

// 注册交互通道
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar> *)registrar {
    [WXApi registerApp:@"wx8131fa0ca06ed1e6" universalLink:@"https://www.xn--vuq861by66a.com"];

    FlutterMethodChannel *channel = [FlutterMethodChannel methodChannelWithName:@"tencent_plugin" binaryMessenger:[registrar messenger]];
    
    TxPlugin *instance = [[TxPlugin alloc] initWithRegistrar:registrar methodChannel:channel];
    [[FlutterWxResponseHandler defaultManager] setMethodChannel:channel];
    [[FlutterQQResponseHandler defaultManager] setMethodChannel:channel];
    [registrar addMethodCallDelegate:instance channel:channel];
    [registrar addApplicationDelegate:instance];
}

// 初始化
- (instancetype)initWithRegistrar:(NSObject <FlutterPluginRegistrar> *)registrar methodChannel:(FlutterMethodChannel *)flutterMethodChannel {
    self = [super init];
    if (self) {
        // 初始化一些操作
        wxApiHandler = [[FlutterWxApiHandler alloc] initWithRegistrar:registrar];
        qqApiHandler = [[FlutterQQApiHandler alloc] initWithRegistrar:registrar];
        [QQSdkCallManager getInstance];
        shareChannel = [FlutterMethodChannel methodChannelWithName:@"channelShare" binaryMessenger:[registrar messenger]];
    }
    return self;
}

// 处理交互方法
- (void)handleMethodCall:(FlutterMethodCall *)call result:(FlutterResult)result {
    if ([call.method isEqualToString:@"getPlatformVersion"]) {
        // 获取平台版本号
        result([@"iOS " stringByAppendingString:[[UIDevice currentDevice] systemVersion]]);
    }
    // 微信
    else if ([call.method isEqualToString:WX_REGISTER]) {
        // 微信注册
        NSLog(@"微信注册=");
        [wxApiHandler wxRegisterWithCall:call result:result];
    } else if ([call.method isEqualToString:WX_IS_INSTALLED]) {
        // 是否安装微信
        NSLog(@"是否安装微信=");
        [wxApiHandler wxIsInstalledWithCall:call result:result];
    } else if ([call.method isEqualToString:WX_AUTH]) {
        // 微信授权
        NSLog(@"微信授权=");
        [wxApiHandler wxAuthWithCall:call result:result];
    } else if ([call.method isEqualToString:WX_SHARE_TEXT]) {
        // 微信分享文本
        NSLog(@"微信分享文本=");
        [wxApiHandler wxShareTextWithCall:call result:result];
    } else if ([call.method isEqualToString:WX_SHARE_IMAGE]) {
        // 微信分享图片
        NSLog(@"微信分享图片=");
        [wxApiHandler wxShareImageWithCall:call result:result];
    } else if ([call.method isEqualToString:WX_SHARE_MUSIC]) {
        // 微信分享音乐
        NSLog(@"微信分享音乐=");
        [wxApiHandler wxShareMusicWithCall:call result:result];
    } else if ([call.method isEqualToString:WX_SHARE_VIDEO]) {
        // 微信分享视频
        NSLog(@"微信分享视频=");
        [wxApiHandler wxShareVideoWithCall:call result:result];
    } else if ([call.method isEqualToString:WX_SHARE_WEB_PAGE]) {
        // 微信分享网页
        NSLog(@"微信分享网页=");
        [wxApiHandler wxShareWebPageWithCall:call result:result];
    } else if ([call.method isEqualToString:WX_SHARE_MINI_PROGRAM]) {
        // 微信分享小程序
        NSLog(@"微信分享小程序=");
        [wxApiHandler wxShareMiniProgramWithCall:call result:result];
    } else if ([call.method isEqualToString:WX_PAY]) {
        // 微信支付
        NSLog(@"微信支付=");
        [wxApiHandler wxPayWithCall:call result:result];
    }
    // QQ
    else if ([call.method isEqualToString:QQ_IS_AUTH_GET_DEVICE_INFO]) {
        // qq是否授权获取设备信息
        [TencentOAuth setIsUserAgreedAuthorization:YES];
    } else if ([call.method isEqualToString:QQ_REGISTER]) {
        // qq注册
        NSLog(@"qq注册=");
        [qqApiHandler qqRegisterWithCall:call result:result];
    } else if ([call.method isEqualToString:QQ_AUTH]) {
        // qq登录
        NSLog(@"qq登录=");
        [qqApiHandler qqAuthWithCall:call result:result];
    } else if ([call.method isEqualToString:QQ_IS_INSTALLED]) {
        // qq是否安装QQ
        NSLog(@"qq是否安装QQ=");
        [qqApiHandler qqIsInstalledWithCall:call result:result];
    } else if ([call.method isEqualToString:QQ_LOGOUT]) {
        // 退出QQ
        NSLog(@"退出QQ=");
        [qqApiHandler qqLogoutWithCall:call result:result];
    } else if ([call.method isEqualToString:QQ_GET_USER_INFO]) {
        // qq获取用户信息
        NSLog(@"qq获取用户信息=");
        [qqApiHandler qqGetUserInfoWithCall:call result:result];
    } else if ([call.method isEqualToString:QQ_SHARE_TEXT]) {
        // 分享文本到QQ
        NSLog(@"分享文本到QQ=");
        [qqApiHandler qqShareTextWithCall:call result:result];
    } else if ([call.method isEqualToString:QQ_SHARE_IMAGE]) {
        // 分享图片到QQ
        NSLog(@"分享图片到QQ=");
        [qqApiHandler qqShareImageWithCall:call result:result];
    } else if ([call.method isEqualToString:QQ_SHARE_MUSIC]) {
        // 分享音乐到QQ
        NSLog(@"分享音乐到QQ=");
        [qqApiHandler qqShareMusicWithCall:call result:result];
    } else if ([call.method isEqualToString:QQ_SHARE_WEB_PAGE]) {
        // 分享网页到QQ
        NSLog(@"分享网页到QQ=");
        [qqApiHandler qqShareWebPageWithCall:call result:result];
    } else {
        // 其他
        result(FlutterMethodNotImplemented);
    }
}

- (NSDictionary *)getParamsWithUrlString:(NSString *)urlString {
    if (urlString.length == 0) {
        NSLog(@"链接为空！");
        return @{};
    }
    //先截取问号
    NSArray *allElements = [urlString componentsSeparatedByString:@"?"];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];//待set的参数字典

    if (allElements.count == 2) {
        //有参数或者?后面为空
        NSString *paramsString = allElements[1];
        //获取参数对
        NSArray *paramsArray = [paramsString componentsSeparatedByString:@"&"];
        if (paramsArray.count >= 2) {
            for (NSInteger i = 0; i < paramsArray.count; i++) {
                NSString *singleParamString = paramsArray[i];
                NSArray *singleParamSet = [singleParamString componentsSeparatedByString:@"="];
                if (singleParamSet.count == 2) {
                    NSString *key = singleParamSet[0];
                    NSString *value = singleParamSet[1];
                    if (key.length > 0 || value.length > 0) {
                        [params setObject:value.length > 0 ? value : @"" forKey:key.length > 0 ? key : @""];
                    }
                }
            }
        } else if (paramsArray.count == 1) {//无 &。url只有?后一个参数
            NSString *singleParamString = paramsArray[0];

            NSArray *singleParamSet = [singleParamString componentsSeparatedByString:@"="];
            if (singleParamSet.count == 2) {
                NSString *key = singleParamSet[0];
                NSString *value = singleParamSet[1];
                if (key.length > 0 || value.length > 0) {
                    [params setObject:value.length > 0 ? value : @""forKey:key.length > 0 ? key : @""];
                }
            } else {
                //问号后面啥也没有 xxxx?  无需处理
            }
        }
        //整合url及参数
        return params;
    } else if (allElements.count > 2) {
        NSLog(@"链接不合法！链接包含多个\"?\"");
        return @{};
    } else {
        NSLog(@"链接不包含参数！");
        return @{};
    }
}

// 处理url scheme
- (void)processUrlScheme:(NSURL *)url {
    // xinxigu://infovalley?type=3&id=5f363472e4b00aa73bee6449

    NSLog(@"url.scheme: %@", [url scheme]);
    NSLog(@"url.absoluteString: %@", [url absoluteString]);

    if ([[url scheme] isEqual:@"xinxigu"]) {
        if ([[url absoluteString] containsString:@"://infovalley?"]) {
            // 通过URL scheme打开APP，跳转指定页面
            NSDictionary *params = [self getParamsWithUrlString:[url absoluteString]];
            [shareChannel invokeMethod:@"openTheActivity" arguments:params result:nil];
        }
    }
}

// MARK: - Application delegate

// 9.0之后新接口
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options {
    NSLog(@"调起信息谷1：%@", [url scheme]);
    
    [QQApiInterface handleOpenURL:url delegate:[FlutterQQResponseHandler defaultManager]];//QQ分享回调url处理
    [TencentOAuth HandleOpenURL:url];//!!!如果不写, 不走QQ登陆回调代理方法
    [WXApi handleOpenURL:url delegate:[FlutterWxResponseHandler defaultManager]];
    if ([[url scheme] isEqual:@"xinxigu"]) {
        [self processUrlScheme:url];
        return YES;
    }
    return NO;
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    NSLog(@"调起信息谷2：%@", [url scheme]);
    
    [QQApiInterface handleOpenURL:url delegate:[FlutterQQResponseHandler defaultManager]];
    [TencentOAuth HandleOpenURL:url];
    [WXApi handleOpenURL:url delegate:[FlutterWxResponseHandler defaultManager]];
    if ([[url scheme] isEqual:@"xinxigu"]) {
        [self processUrlScheme:url];
        return YES;
    }
    return NO;
}

// Universal Links
- (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void (^)(NSArray<id<UIUserActivityRestoring> > *__nullable restorableObjects))restorationHandler
{
    // Demo处理手Q UniversalLink回调的示例代码
    if ([userActivity.activityType isEqualToString:NSUserActivityTypeBrowsingWeb]) {
        NSURL *url = userActivity.webpageURL;
        
        NSLog(@"调起信息谷3：%@", [url scheme]);
        
        if (url && [TencentOAuth CanHandleUniversalLink:url]) {
            // 兼容[QQApiInterface handleOpenURL:delegate:]的接口回调能力
            [QQApiInterface handleOpenUniversallink:url delegate:(id<QQApiInterfaceDelegate>)[FlutterQQResponseHandler defaultManager]];
            return [TencentOAuth HandleUniversalLink:url];
        }
    }

    [WXApi handleOpenUniversalLink:userActivity delegate:[FlutterWxResponseHandler defaultManager]];

    return YES;
}

- (BOOL)handleOpenURL:(NSNotification *)aNotification {
    NSString *aURLString = [aNotification userInfo][@"url"];
    NSURL *aURL = [NSURL URLWithString:aURLString];
    NSLog(@"aURL: %@", aURL);
    
    NSLog(@"调起信息谷4：%@", [aURL scheme]);
    
    [WXApi handleOpenURL:aURL delegate:[FlutterWxResponseHandler defaultManager]];
    [QQApiInterface handleOpenURL:aURL delegate:[FlutterQQResponseHandler defaultManager]];
    return YES;
}

@end
